package com.xxxy.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author sjh
 * @date 2022/1/29 16:20
 */
@Slf4j
public class ExcelDemoUtils {

    public static <T>AnalysisEventListener<T> getListener(Consumer<List<T>> consumer, int threshold){
        return new AnalysisEventListener<T>() {
            private LinkedList<T> linkedList = new LinkedList<T>();
            @Override
            public void invoke(T t, AnalysisContext analysisContext) {
                linkedList.add(t);
                if(linkedList.size() == threshold){
                    consumer.accept(linkedList);
                    linkedList.clear();
                }
                log.info("解析到一条数据:{}", JSON.toJSONString(t));
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                if(linkedList.size() > 0){
                    consumer.accept(linkedList);
                }
                log.info("所有数据解析完成！");
            }
        };
    }

    public static <T>AnalysisEventListener<T> getListener(Consumer<List<T>> consumer){
        return getListener(consumer, 10);
    }
}
